<template>
  <div class="page">
    <global-header title="游戏设置" @back="$router.back()">
      <template #right>
        <div class="mr-[10px] text-[15px]" @click="handleSave">保存</div>
      </template>
    </global-header>
    <main class="page-main">
      <loading v-if="state.loading" />
      <template v-else>
        <section v-for="item in state.list" class="bg-[#fff]">
          <article
            class="flex justify-between items-center py-[10px]"
            @click="item.Checked = !item.Checked"
          >
            <div class="flex-1 w-0 flex items-center pl-[15px]">
              <img class="w-[30px] h-[30px] rounded-full" :src="lotteryLogo(item.LotteryId)" />
              <div class="ml-[10px] text-[14px]">{{ item.Name }}</div>
            </div>
            <div class="flex items-center pr-[15px]" @click.stop>
              <van-switch
                class="!text-[22px]"
                :model-value="item.Status"
                :active-value="1"
                :inactive-value="0"
                @update:model-value="(val: number) => onUpdateValue(val, item)"
              />
            </div>
            <div class="flex items-center pr-[15px]">
              <span class="arrow" :class="{ rotate: item.Checked }">
                <van-icon name="arrow-down" class="!text-[16px]" color="#999" />
              </span>
            </div>
          </article>
          <article class="border-bottom bg-[#f8f8f8]" v-if="item.Checked">
            <div class="text-[12px] py-[10px] px-[15px] text-red">
              注意：提前封盘时间请参考盘内封盘时间设置，最优选择是比盘内提前封盘，否则可能导致飞单失败。
            </div>
            <ul class="list-box">
              <li>
                <div>序号</div>
                <div>
                  <van-field :max="100" :min="0" v-model="item.LotterySort" type="digit" />
                </div>
              </li>
              <li>
                <div>提前封盘时间/秒</div>
                <div class="flex justify-between items-center">
                  <div class="flex-1 w-0">
                    <van-field :max="60" :min="0" v-model="item.CloseCount" type="digit" />
                  </div>
                  <div class="ml-[10px]">
                    <van-button
                      size="mini"
                      class="!px-[10px] !text-[12px]"
                      @click="handlePatch(item.CloseCount, 'CloseCount')"
                    >
                      批量
                    </van-button>
                  </div>
                </div>
              </li>
              <li>
                <div>自动开启</div>
                <div class="flex justify-between items-center">
                  <div class="text-[14px]" @click="handleShowPicker(item, 'OpenTime')">
                    <van-icon name="clock-o" />
                    <span class="ml-[5px]">{{ item.OpenTime }}</span>
                  </div>
                  <div>
                    <van-button
                      size="mini"
                      class="!px-[10px] !text-[12px]"
                      @click="handlePatch(item.OpenTime, 'OpenTime')"
                    >
                      批量
                    </van-button>
                  </div>
                </div>
              </li>
              <li>
                <div>自动结束</div>
                <div class="flex justify-between items-center">
                  <div class="text-[14px]" @click="handleShowPicker(item, 'CloseTime')">
                    <van-icon name="clock-o" />
                    <span class="ml-[5px]">{{ item.CloseTime }}</span>
                  </div>
                  <div>
                    <van-button
                      size="mini"
                      class="!px-[10px] !text-[12px]"
                      @click="handlePatch(item.CloseTime, 'CloseTime')"
                    >
                      批量
                    </van-button>
                  </div>
                </div>
              </li>
              <li>
                <div>是否允许取消注单</div>
                <div class="flex justify-between items-center">
                  <van-switch
                    class="!text-[22px]"
                    v-model="item.CancelEnable"
                    :active-value="1"
                    :inactive-value="0"
                  />
                  <div>
                    <van-button
                      size="mini"
                      class="!px-[10px] !text-[12px]"
                      @click="handlePatch(item.CancelEnable, 'CancelEnable')"
                    >
                      批量
                    </van-button>
                  </div>
                </div>
              </li>
            </ul>
          </article>
        </section>
      </template>
    </main>
    <div class="mx-[15px] py-[10px]">
      <div class="flex justify-between items-center rounded-full overflow-hidden">
        <van-button class="!flex-1 !rounded-none !border-0" block @click="handleAllOpen(0)">
          一键关闭
        </van-button>
        <van-button
          class="!flex-1 !rounded-none !border-0"
          block
          type="primary"
          @click="handleAllOpen(1)"
        >
          一键开启
        </van-button>
      </div>
    </div>
    <van-popup round position="bottom" v-model:show="state.showPicker" destroy-on-close>
      <van-time-picker
        @cancel="state.showPicker = false"
        @confirm="handleConfirm"
        :model-value="state.picker"
        title="选择时间"
        :columns-type="['hour', 'minute', 'second']"
      />
    </van-popup>
  </div>
</template>
<route>
  {
    name: "admin-setting-game",
    meta: {
      pageIndex: 3,
    }
  }
</route>
<script setup lang="ts">
import { reqSwitchStatus } from "@/api/main";
import { reqGameSettingShow, reqGameSettingSwitch } from "@/api/setting";
import { usePremsStore } from "@/store/modules/prems";
import { lotteryLogo } from "@/utils/game";
import { toast } from "@/utils/toast";
import { cloneDeep, debounce } from "lodash-es";

type KeyMo = keyof GameListMo;
const state = reactive({
  loading: false,
  updating: false,
  list: <GameListMo[]>[],
  cloneList: <GameListMo[]>[],
  picker: ["12", "00", "00"],
  pickerType: "OpenTime",
  showPicker: false
});
const premsStore = usePremsStore();
const cur = ref<GameListMo | null>(null);

// 获取数据
const getData = async () => {
  try {
    state.loading = true;
    const res = await reqGameSettingShow();
    state.loading = false;
    const data = cloneDeep(
      res.data.map(item => {
        return {
          ...item,
          Checked: false
        };
      })
    );
    data.sort((a, b) => {
      if (a.LotterySort !== b.LotterySort) {
        return a.LotterySort - b.LotterySort;
      }
      return a.LotteryId - b.LotteryId;
    });
    state.list = data;
    state.cloneList = cloneDeep(state.list);
  } catch (e) {
    state.loading = false;
    console.log(e);
  }
};

// 打开选择时间
const handleShowPicker = (item: GameListMo, type: "OpenTime" | "CloseTime") => {
  cur.value = item;
  state.pickerType = type;
  if (type == "OpenTime") {
    state.picker = item.OpenTime.split(":");
  } else {
    state.picker = item.CloseTime.split(":");
  }
  nextTick(() => {
    state.showPicker = true;
  });
};

// 确认选择时间
const handleConfirm = ({ selectedValues }: any) => {
  if (cur.value) {
    const list = cloneDeep(state.list);
    list.forEach(item => {
      if (item.LotteryId == cur.value?.LotteryId) {
        if (state.pickerType == "OpenTime") {
          item.OpenTime = selectedValues.join(":");
        } else {
          item.CloseTime = selectedValues.join(":");
        }
      }
    });
    state.list = cloneDeep(list);
    state.picker = ["00", "00", "00"];
    state.showPicker = false;
  }
};

// 修改状态
const onUpdateValue = async (newValue: number, item: GameListMo) => {
  if (!premsStore.isEditGameSetting) {
    toast.info("暂无权限");
    return;
  }
  try {
    await reqSwitchStatus({
      LotteryId: item.LotteryId,
      Status: newValue
    });
    item.Status = newValue;
    toast.info("设置成功");
  } catch (error) {
    console.log(error);
  }
};

const handlePatch = (val: any, key: KeyMo) => {
  const list = cloneDeep(
    state.list.map(item => {
      return {
        ...item,
        [key]: val
      };
    })
  );
  state.list = cloneDeep(list);
};

// 一键开启、关闭
const handleAllOpen = async (key: number) => {
  if (!premsStore.isEditGameSetting) {
    toast.info("暂无权限");
    return;
  }
  const loading = toast.loading("设置中...");
  try {
    const list = cloneDeep(
      state.list.map(item => {
        return {
          LotteryId: Number(item.LotteryId),
          Status: key,
          CancelEnable: Number(item.CancelEnable),
          CloseCount: Number(item.CloseCount),
          CloseTime: item.CloseTime,
          OpenTime: item.OpenTime,
          LotterySort: Number(item.LotterySort)
        };
      })
    );
    await reqGameSettingSwitch({
      List: list
    });
    loading.close();
    state.list = cloneDeep(
      state.list.map(item => {
        return {
          ...item,
          Status: key
        };
      })
    );
    toast.info("设置成功");
  } catch (error) {
    loading.close();
    console.log(error);
  }
};

// 保存
const handleSave = debounce(
  async () => {
    if (!premsStore.isEditGameSetting) {
      toast.info("暂无权限");
      return;
    }
    if (JSON.stringify(state.list) == JSON.stringify(state.cloneList)) {
      toast.info("暂无修改");
      return;
    }
    try {
      state.updating = true;
      const list = cloneDeep(
        state.list.map(item => {
          return {
            LotteryId: Number(item.LotteryId),
            Status: Number(item.Status),
            CancelEnable: Number(item.CancelEnable),
            CloseCount: Number(item.CloseCount),
            CloseTime: item.CloseTime,
            OpenTime: item.OpenTime,
            LotterySort: Number(item.LotterySort)
          };
        })
      );
      await reqGameSettingSwitch({
        List: list
      });

      state.updating = false;
      toast.success("保存成功");
    } catch (error) {
      state.updating = false;
      console.log(error);
    }
  },
  300,
  { leading: true, trailing: false }
);

onMounted(() => {
  getData();
});
</script>
<style lang="scss" scoped>
.arrow {
  transition: transform 0.3s ease;
  width: 12px;
  height: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.arrow.rotate {
  transform: rotate(180deg);
}
.list-box {
  li {
    display: flex;
    padding: 10px 15px;
    justify-content: space-between;
    align-items: center;
    > div:first-child {
      width: 120px;
      padding-right: 10px;
      font-size: 14px;
    }
    > div:last-child {
      flex: 1;
      width: 0;
      .van-field {
        border: 1px solid #ccc;
        border-radius: 8px;
        background-color: #fff;
        padding: 4px 10px;
      }
    }
  }
}
</style>
